package com.chuji.crmcj.act;

import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.chuji.crmcj.R;
import com.chuji.crmcj.bean.MagNoticeSalesInfo;
import com.chuji.crmcj.bean.SaleNoticeDatailInfo;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;
import com.jauker.widget.BadgeView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by w.pitt on 2016/1/22.
 */
public class NoticeDetailAct extends BaseActivity implements View.OnClickListener {
    //返回
    private ImageView mIv_Back;
    //标题
    private TextView mTv_action_title;
    //内容
    private TextView mTv_notice_content;
    //时间
    private TextView mTv_time;
    //未读列表
    private LinearLayout mLl_no_read;
    //已读列表
    private LinearLayout mLl_read;
    private ImageView mJiantou1;
    private ImageView mJiantou2;
    private View mXiahuaxian1;
    private View mXiahuaxian2;
    //未读数目
    private TextView mTv_not_read_num;
    //接收人数目
    private TextView mTv_recieve;
    //未读销售员列表
    private ListView mLv_notice_no_read;
    //未读销售员列表适配器
    private CustomNoticeDatailAdapter customNoticeDatailAdapter;
    //已读数目
    private TextView mTv_read_num;
    //接收人数目
    private TextView mTv_recieve_num;
    //已读销售员列表
    private ListView mLv_notice_read;
    //已读销售员列表适配器
    private CustomNoticeSalesAdapter customNoticeSalesAdapter;
    //数据存储
    List<SaleNoticeDatailInfo.ApiParamObjEntity> saleNoticeDatailData;
    //网络数据
    private SaleNoticeDatailInfo saleNoticeDatailInfo;
    //数据存储
    List<MagNoticeSalesInfo.ApiParamObjEntity> magNoticeSalesData;
    //网络数据
    private MagNoticeSalesInfo magNoticeSalesInfo;
    //消息ID
    String MessageID;
    //用户ID
    String UserID;
    //判断是否显示
    boolean isShow=true;
    @Override
    protected void initView() {
        setContentView(R.layout.act_notice_detail);
        mIv_Back = (ImageView) findViewById(R.id.iv_Back);
        mTv_action_title = (TextView) findViewById(R.id.tv_action_title);
        mTv_notice_content = (TextView) findViewById(R.id.tv_notice_content);
        mTv_time = (TextView) findViewById(R.id.tv_time);
        mTv_not_read_num = (TextView) findViewById(R.id.tv_not_read_num);
        mTv_recieve = (TextView) findViewById(R.id.tv_recieve);
        mLv_notice_no_read = (ListView) findViewById(R.id.lv_notice_no_read);
        mTv_read_num = (TextView) findViewById(R.id.tv_read_num);
        mTv_recieve_num = (TextView) findViewById(R.id.tv_recieve_num);
        mLv_notice_read = (ListView) findViewById(R.id.lv_notice_read);
        mLl_no_read = (LinearLayout) findViewById(R.id.ll_no_read);
        mLl_read = (LinearLayout) findViewById(R.id.ll_read);
        mJiantou1 = (ImageView) findViewById(R.id.jiantou1);
        mJiantou2 = (ImageView) findViewById(R.id.jiantou2);
        mXiahuaxian1 = (View) findViewById(R.id.xiahuaxian1);
        mXiahuaxian2 = (View) findViewById(R.id.xiahuaxian2);
        //数据
        initDa();
        //点击
        mIv_Back.setOnClickListener(this);
        mLl_no_read.setOnClickListener(this);
        mLl_read.setOnClickListener(this);
        //默认隐藏
        mLv_notice_no_read.setVisibility(View.GONE);
        mLv_notice_read.setVisibility(View.GONE);
        mXiahuaxian1.setVisibility(View.GONE);
        mXiahuaxian2.setVisibility(View.GONE);
    }
    public void initDa() {
        /*通知详情*/
        getNoticeData();
        /*通知人数（未读/已读）*/
        getNoticeSales();
    }
    private void getNoticeData() {
        //第一次
        if (saleNoticeDatailData == null) {
            saleNoticeDatailData = new ArrayList<SaleNoticeDatailInfo.ApiParamObjEntity>();
        }
        //初始化Volley
        UserID= SPUtils.getString(UIUtils.getContext(),"UserID","");
        Intent intent=getIntent();
        MessageID=intent.getStringExtra("MessageID");
        String strURL = String.format(UrlUtils.SALES_NOTICE_DETAIL+"&UserID="+ UserID+"&defeatType=1"+"&MessageID="+MessageID);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                saleNoticeDatailInfo = JSON.parseObject(response, SaleNoticeDatailInfo.class);
                saleNoticeDatailData.addAll(saleNoticeDatailInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (saleNoticeDatailData.size() != 0) {
                            mTv_action_title.setText(saleNoticeDatailData.get(0).getTitle());
                            mTv_time.setText(saleNoticeDatailData.get(0).getSendTime());
                            mTv_notice_content.setText(saleNoticeDatailData.get(0).getContent());
                            mTv_recieve.setText(String.valueOf(saleNoticeDatailInfo.getCount()));
                            mTv_recieve_num.setText(String.valueOf(saleNoticeDatailInfo.getCount()));
                        } else {
                            UIUtils.showToastSafe("暂无数据");
                        }
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    private void getNoticeSales() {
        //第一次
        if (magNoticeSalesData == null) {
            magNoticeSalesData = new ArrayList<MagNoticeSalesInfo.ApiParamObjEntity>();
        }
        //初始化Volley
        Intent intent=getIntent();
        MessageID=intent.getStringExtra("MessageID");
        String strURL = String.format(UrlUtils.MAG_NOTICE_DETAIL_SALES+"&UserID="+ UserID+"&defeatType=1"+"&MessageID="+MessageID);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                magNoticeSalesInfo = JSON.parseObject(response, MagNoticeSalesInfo.class);
                magNoticeSalesData.addAll(magNoticeSalesInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (magNoticeSalesData.size()!= 0) {
                            if(magNoticeSalesData.get(0).getIsRead()=="0"){
                                // 判断adapter是否创建
                                if (customNoticeDatailAdapter == null) {
                                    customNoticeDatailAdapter = new CustomNoticeDatailAdapter();
                                    mLv_notice_no_read.setAdapter(customNoticeDatailAdapter);
                                    if(magNoticeSalesData.size()==0){
                                        mTv_not_read_num.setText("0");
                                    }else {
                                        mTv_not_read_num.setText(String.valueOf(magNoticeSalesData.size()));
                                    }
                                    setListViewHeightBasedOnChildren(mLv_notice_no_read);
                                } else {
                                    customNoticeDatailAdapter.notifyDataSetChanged();
                                }
                            }else{
                                // 判断adapter是否创建
                                if (customNoticeSalesAdapter == null) {
                                    customNoticeSalesAdapter = new CustomNoticeSalesAdapter();
                                    mLv_notice_read.setAdapter(customNoticeSalesAdapter);
                                    if(magNoticeSalesData.size()==0){
                                        mTv_read_num.setText("0");
                                    }else {
                                        mTv_read_num.setText(String.valueOf(magNoticeSalesData.size()));
                                    }
                                    setListViewHeightBasedOnChildren(mLv_notice_read);
                                } else {
                                    customNoticeSalesAdapter.notifyDataSetChanged();
                                }
                            }
                        } else {
                            mTv_not_read_num.setText("0");
                            mTv_read_num.setText("0");
                            UIUtils.showToastSafe("暂无数据");
                        }
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
//    private void getNoticeReadSales() {
//        //第一次
//        if (magNoticeSalesData == null) {
//            magNoticeSalesData = new ArrayList<MagNoticeSalesInfo.ApiParamObjEntity>();
//        }
//        //初始化Volley
//        MessageID="1227FC37-8E05-43ED-BE86-0CE5A401FD6F";
//        String strURL = String.format(UrlUtils.MAG_NOTICE_DETAIL_SALES+"&UserID="+"1227FC37-8E05-43ED-BE86-0CE5A401FD6F"+"&defeatType=1"+"&MessageID="+MessageID);
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String response) {
//                magNoticeSalesInfo = JSON.parseObject(response, MagNoticeSalesInfo.class);
//                magNoticeSalesData.addAll(magNoticeSalesInfo.getApiParamObj());
//                UIUtils.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (magNoticeSalesData.size() != 0) {
//
//
//                        } else {
//                            UIUtils.showToastSafe("暂无数据");
//                        }
//                    }
//                });
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                error.printStackTrace();
//                System.out.println("失败" + error);
//                UIUtils.showToastSafe("请检查网络");
//            }
//        });
//        // Add the request to the RequestQueue.
//        VolleyUtil.getRequestQueue().add(stringRequest);
//    }
    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_Back:
                finish();
                break;
            case R.id.ll_no_read:
                if(isShow) {
//                    mLv_notice_read.setVisibility(View.GONE);
                    mJiantou1.setImageResource(R.drawable.jiantou_shang);
//                    mJiantou2.setImageResource(R.drawable.jiantou_xia);
                    mLv_notice_no_read.setVisibility(View.VISIBLE);
                    mXiahuaxian1.setVisibility(View.VISIBLE);
                    isShow=false;
                }else{
                    //mLv_notice_read.setVisibility(View.GONE);
                    mJiantou1.setImageResource(R.drawable.jiantou_xia);
//                    mJiantou2.setImageResource(R.drawable.jiantou_xia);
                    mLv_notice_no_read.setVisibility(View.GONE);
                    mXiahuaxian1.setVisibility(View.GONE);
                    isShow=true;
                }
                break;
            case R.id.ll_read:
                if(isShow){
                    mLv_notice_read.setVisibility(View.VISIBLE);
//                    mJiantou1.setImageResource(R.drawable.jiantou_xia);
                    mJiantou2.setImageResource(R.drawable.jiantou_shang);
                    mXiahuaxian2.setVisibility(View.VISIBLE);
//                    mLv_notice_no_read.setVisibility(View.GONE);
                    isShow=false;
                }else {
                    mLv_notice_read.setVisibility(View.GONE);
//                    mJiantou1.setImageResource(R.drawable.jiantou_xia);
                    mJiantou2.setImageResource(R.drawable.jiantou_xia);
//                    mLv_notice_no_read.setVisibility(View.GONE);
                    mXiahuaxian2.setVisibility(View.GONE);
                    isShow=true;
                }
                break;
        }
    }
    /**
     * 自定义适配器
     */
    class CustomNoticeDatailAdapter extends BaseAdapter {

        private Context context;

        @Override
        public int getCount() {
            return magNoticeSalesData.size();
        }

        @Override
        public Object getItem(int i) {
            return magNoticeSalesData.get(i);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            /****1)根据list_item.xml--》得到当前子项元素的布局   【界面】*******/
            //b)声明ViewHolder
            ViewHolder viewHolder = null;
            //c)判断convertView是否为null
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_notice_sales_num, null);
                //初始化组件
                viewHolder.mIv_client_image = (com.chuji.crmcj.view.CircleImageView) convertView.findViewById(R.id.iv_client_image);
                viewHolder.mTv_sales_name = (TextView) convertView.findViewById(R.id.tv_sales_name);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if(magNoticeSalesData.size()!=0) {
                viewHolder.mTv_sales_name.setText(magNoticeSalesData.get(position).getRealName());
                if (magNoticeSalesData.get(position).getIsRead()=="0"){
                    if(magNoticeSalesData.get(position).getAvatar()!=null){
                        Glide.with(UIUtils.getContext())
                                .load(UrlUtils.ImageIP + magNoticeSalesData.get(position).getAvatar())
                                .into(viewHolder.mIv_client_image);
                    }else{
                        viewHolder.mIv_client_image.setImageResource(R.drawable.morentouxiang);
                    }
                }
            }else{
                UIUtils.showToastSafe("暂无数据");
            }
            return convertView;
        }
    }
    static class ViewHolder {
        private com.chuji.crmcj.view.CircleImageView mIv_client_image;
        private TextView mTv_sales_name;
    }
    /**
     * 自定义适配器
     */
    class CustomNoticeSalesAdapter extends BaseAdapter {

        private Context context;

        @Override
        public int getCount() {
            return magNoticeSalesData.size();
        }

        @Override
        public Object getItem(int i) {
            return magNoticeSalesData.get(i);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            /****1)根据list_item.xml--》得到当前子项元素的布局   【界面】*******/
            //b)声明ViewHolder
            ViewHolder viewHolder = null;
            //c)判断convertView是否为null
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_notice_sales_num, null);
                //初始化组件
                viewHolder.mIv_client_image = (com.chuji.crmcj.view.CircleImageView) convertView.findViewById(R.id.iv_client_image);
                viewHolder.mTv_sales_name = (TextView) convertView.findViewById(R.id.tv_sales_name);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if(magNoticeSalesData.size()!=0) {
                viewHolder.mTv_sales_name.setText(magNoticeSalesData.get(position).getRealName());
                if (magNoticeSalesData.get(position).getIsRead()=="0"){
                    if(magNoticeSalesData.get(position).getAvatar()!=null){
                        Glide.with(UIUtils.getContext())
                                .load(UrlUtils.MAG_NOTICE_FORM + magNoticeSalesData.get(position).getAvatar())
                                .into(viewHolder.mIv_client_image);
                    }else{
                        viewHolder.mIv_client_image.setImageResource(R.drawable.morentouxiang);
                    }
                }
            }else{
                UIUtils.showToastSafe("暂无数据");
            }
            return convertView;
        }
    }
    //手动设置Listview的高度
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null) return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}
